package handler

import (
	"daily14/cache"
	"daily14/model"
	"daily14/pkg"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}

	user := model.User{
		Username: username,
		Password: password,
	}
	redis_key := "user_login_" + username
	errCont, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCont >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败3次,禁止登录",
		})
		return
	}

	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCont == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登录成功",
	})
	return

}
